    //
//  ItemDetailViewController.m
//  Menu
//
//  Created by trimad on 11-11-21.
//  Copyright 2011 Trimad Group. All rights reserved.
//

#import "DisplayManager.h"
#import "ItemDetailViewController.h"
#import "Item.h"
#import "ItemDetailView.h"
#import "Page.h"

@interface ItemDetailViewController(Private) 

-(NSArray *) getItemDetailViewArrayInPage:(int)pageIndex;
-(ItemDetailView *) getItemDetailView :(Item *)item;
-(void) preloadItemDetailViews;
-(void) drawScrollView;
@end

@implementation ItemDetailViewController

@synthesize scrollView;

Item *startItem;
/* 当前显示的Item View的索引*/
int currentItemIndex = 0;
/* 当前加载的Item View的总数*/
int currentItemCount = 0;
/* 当前显示的Item所在的页码*/
int currentPageIndex = 1;
/* 当前加载的Item View Array*/
NSMutableArray *itemDetailViewArray;
NSMutableArray *addedItemArray;

static int PRELOAD_THREHOLD = 1;
static int SCROLL_VIEW_WIDTH = 768;
static int SCROLL_VIEW_HEIGHT = 1024;

- (id)initWithNibName:(NSString *)nibNameOrNil 
			   bundle:(NSBundle *)nibBundleOrNil pageIndex:(Item *)item {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        startItem = item;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
	
	itemDetailViewArray = [[NSMutableArray alloc] init];
	addedItemArray = [[NSMutableArray alloc] init];
	currentPageIndex = [[DisplayManager instance] pageIndex:startItem.code];
	
	NSArray *itemDetailViews = [self getItemDetailViewArrayInPage:currentPageIndex];
	currentItemCount = itemDetailViews.count;
	ItemDetailView *aItemDetailView;
	
	for (int i = 0; i < itemDetailViews.count; i++) {
		aItemDetailView = [itemDetailViews objectAtIndex:i];
		[itemDetailViewArray addObject:aItemDetailView];
		if ([aItemDetailView.item.code isEqual: startItem.code]) {
			currentItemIndex = i;
		}
	}
	[itemDetailViews release];
	
	[self preloadItemDetailViews];
}

-(void)drawScrollView {
	ItemDetailView *aItemDetailView;
	for (int i = 0; i < itemDetailViewArray.count; i++) {
		CGRect frame;
		frame.origin.x = SCROLL_VIEW_WIDTH * i;
		frame.origin.y = 0;
		frame.size.height = SCROLL_VIEW_HEIGHT;
		frame.size.width = SCROLL_VIEW_WIDTH;
		
		aItemDetailView = [itemDetailViewArray objectAtIndex:i];
		aItemDetailView.frame = frame;
		[self.scrollView addSubview:aItemDetailView];
	}
	
	// 获取滚动View总宽度
	self.scrollView.contentSize = CGSizeMake(
										SCROLL_VIEW_WIDTH * currentItemCount, 
										SCROLL_VIEW_HEIGHT);
	
	// 滚动到当前选中的ItemView
	CGPoint point;
	point.x = SCROLL_VIEW_WIDTH * currentItemIndex;
	point.y = 0;
	self.scrollView.contentOffset = point;
}

/*
 * 预加载前后页的ItemDetailView
 */
-(void) preloadItemDetailViews {
	if (currentItemIndex - PRELOAD_THREHOLD <= 0) {
		if (currentPageIndex > 1) {
			/* 如果前面的ItemDetailView只剩一个，并且当前页不是第一页，则需要预加载前一页的ItemDetailView(s)，*/
			
			NSArray *itemDetailViews = [self getItemDetailViewArrayInPage:currentPageIndex - 1];
			if (itemDetailViews != nil) {
				currentItemCount += itemDetailViews.count;
				currentItemIndex += itemDetailViews.count;
				ItemDetailView *aItemDetailView;
				
				//从后向前插入到第一个subview位置
				for (int i = itemDetailViews.count - 1; i >= 0; i--) {
					aItemDetailView = [itemDetailViews objectAtIndex:i];
					[itemDetailViewArray insertObject:aItemDetailView atIndex:0];
				}
				
				[itemDetailViews release];
			}
		}
	}
	if (currentItemIndex + PRELOAD_THREHOLD >= currentItemCount) {
		/* 如果后面的ItemDetailView只剩一个，则需要预加载后一页的ItemDetailView(s)，*/
		NSArray *itemDetailViews = [self getItemDetailViewArrayInPage:currentPageIndex + 1];
		if (itemDetailViews != nil) {
			currentItemCount += itemDetailViews.count;
			ItemDetailView *aItemDetailView;
			for (int i = 0; i < itemDetailViews.count; i++) {
				aItemDetailView = [itemDetailViews objectAtIndex:i];
				[itemDetailViewArray addObject:aItemDetailView];
			}
			
			[itemDetailViews release];
		}
	}
	
	[self drawScrollView];
}

-(NSArray *) getItemDetailViewArrayInPage:(int)pageIndex {
	Page *page = [[DisplayManager instance] page:pageIndex];
	NSArray *items = page.items;
	NSMutableArray *itemDetailViews = [[NSMutableArray alloc] initWithCapacity:items.count];
	
	Item * aItem;
	for (int i = 0; i < items.count; i++) {
		aItem = [items objectAtIndex:i];
		if (aItem.itemType != AdItem && ![addedItemArray containsObject:aItem.code]) {
			ItemDetailView *itemDetailView = [self getItemDetailView:aItem];
			[itemDetailViews addObject:itemDetailView];
			[addedItemArray addObject:aItem.code];
		}

	}
	return itemDetailViews;
}

-(ItemDetailView *) getItemDetailView:(Item *)item {
	ItemDetailView *itemDetailView = [[[NSBundle mainBundle] loadNibNamed:@"ItemDetailView" owner:self options:nil] 
							  objectAtIndex:0];
	[itemDetailView activate:item];
	return itemDetailView;
}

/* 每次滑动结束后进行预加载*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = SCROLL_VIEW_WIDTH;
    currentItemIndex = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    ItemDetailView * itemDetailView = [self.scrollView.subviews objectAtIndex:currentItemIndex];
	currentPageIndex = [[DisplayManager instance] pageIndex:itemDetailView.item.code];
	
	//预加载
	[self preloadItemDetailViews];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[itemDetailViewArray release];
    [super dealloc];
}


@end
